import { Injectable } from '@angular/core';
import { Action, State, StateContext } from '@ngxs/store';
import { SystemAction } from './system.action';
import { Clipboard } from '@angular/cdk/clipboard';
import { NzMessageService } from 'ng-zorro-antd/message';
import { HttpClient } from '@angular/common/http';
import { mergeMap, tap } from 'rxjs';
import { DemoAction } from '../demo';

export interface SystemStateModel {
  /**临时数据*/
  tempData?: any;
  /**菜单栏是否收缩，默认否*/
  isCollapsed: boolean;
  /**是否登录*/
  isLogin: boolean;
  token?: string;
  emailAddr?: string;
}

@State<SystemStateModel>({
  name: 'system',
  defaults: {
    tempData: undefined,
    isCollapsed: false,
    emailAddr: undefined,
    isLogin: false,
  },
})
@Injectable({
  providedIn: 'root',
})
export class SystemState {

  constructor(
      private clipboard: Clipboard,
      private message: NzMessageService,
      private http: HttpClient,
  ) {
  }

  @Action(SystemAction.SaveTempData)
  saveTempData(ctx: StateContext<SystemStateModel>, {data}: SystemAction.SaveTempData) {
    ctx.patchState({tempData: data});
  }

  @Action(SystemAction.Copy)
  copyText(ctx: StateContext<SystemStateModel>, data: SystemAction.Copy) {
    this.clipboard.copy(data.text);
    if (!!data.title) {
      this.message.create('success', data.title);
    } else {
      this.message.create('success', `复制成功`);
    }
  }

  @Action(SystemAction.Jump)
  jump(ctx: StateContext<SystemStateModel>, data: SystemAction.Jump) {
    window.open(data.url);
  }

  @Action(SystemAction.ChangeCollapsed)
  ChangeCollapsed(ctx: StateContext<SystemStateModel>) {
    let isCollapsed = ctx.getState().isCollapsed;
    ctx.patchState({isCollapsed: !isCollapsed});
  }

  @Action(SystemAction.Login)
  Login(ctx: StateContext<SystemStateModel>, {data}: SystemAction.Login) {
    let token = `Basic ${btoa(data.username + ':' + data.password)}`;
    const headers = {
      'Authorization': token,
    };
    return this.http.get(`/api/codeforfun-statistics-backend/data/list`, {headers}).pipe(tap({
      next: () => {
        ctx.patchState({isLogin: true, token: token});
        this.message.success(`登录成功`);
      },
      error: () => {
        this.message.error(`登录失败`);
      },
    }), mergeMap(() => ctx.dispatch(new DemoAction.ResetData())));
  }

  @Action(SystemAction.Logout)
  Logout(ctx: StateContext<SystemStateModel>) {
    ctx.patchState({isLogin: false, token: undefined});
  }

  @Action(SystemAction.SaveEmailAddr)
  SaveEmailAddr(ctx: StateContext<SystemStateModel>, {emailAddr}: SystemAction.SaveEmailAddr) {
    ctx.patchState({emailAddr: emailAddr});
  }

}
